<?php
namespace app\index\service;

use app\common\ConfigBase;
use app\common\model\ToolModel;

class DistributionService
{
    //配送类型
    static public $psStatus=[
        1=>'调拨'
        ,2=>'采销'
    ];
     //审核类型
    static public $auditStatus=[
        0=>'未提交'
        ,1=>'待审核'
        ,2=>'已审核'
        ,3=>'已驳回'
    ];
  /**
     *上传发运明细处理
     * @param $data
     * @return array
     * @author xiejunyu
     */
    static public function uploadHandle($data,$param){
        $msg=[];//提示信息
        $sku=[];
        $getShop=ConfigBase::getShopKeyName();
        $getShopNames=array_keys($getShop);
        $res=[];
        $skuShop=[];
        foreach ($data as $k=>&$v){
            $line=$k+2;
            if(empty($v[0])){
                $msg[]="第{$line}行sku不能为空";
            }
            if(!preg_match("/^[1-9][0-9]*$/",$v[1])){
                $msg[]="第{$line}行计划数量必须为正整数";
            }
            $v[0]=strtoupper($v[0]);
            $sku[]=$v[0];
        }
        if(!empty($msg)){
            return returnArr(500,$msg);
        }
        $skuInfo=\app\common\service\SkuService::getBatchInfoBySku($sku,['cnname']);
        if(empty($skuInfo)){
            $msg[]="SKU信息获取失败!";
        }
        $where=[
            "warehouse_id"=>$param['warehouse_id']
        ];
        $ware=ConfigBase::getinStockPrice();
        
      /*  if(empty($ware)){
            $msg[]="SKU仓库库存获取失败!";
        }*/
        foreach ($data as $k2=>$v2){
            
            $temp=[];
            $temp['sku']=$v2[0];
            $available_stock=isset($ware[$param['warehouse_id']."_".$temp['sku']]) ? $ware[$param['warehouse_id']."_".$temp['sku']]['available_stock'] : 0;
            $price=isset($ware[$param['warehouse_id']."_".$temp['sku']]) ? $ware[$param['warehouse_id']."_".$temp['sku']]['wam'] : 0;
            if(empty($skuInfo[$temp['sku']])){
                $msg[]="sku:{$temp['sku']}在基础资料不存在";
                continue;
            }
            if(!($available_stock>0 && $price>0)){
                $msg1="sku:{$temp['sku']}库存不存在";
                return returnArr(500,$msg1);
            }
            if($available_stock<$v2[1]){
                $msg1="sku:{$temp['sku']}库存不够，不能创建计划";
                return returnArr(500,$msg1);
            }
            $temp['sku_name']=$skuInfo[$temp['sku']]['cnname']??'';
            $temp['quantity']=$v2[1];
            $temp['price']=$price;
            $temp['available_stock']=$available_stock;
            $res[]=$temp;
        }
        if(!empty($msg)){
            return returnArr(500,$msg);
        }
        return returnArr(1,'',$res);
    }
    static public function edit($param){

    }

    /**
     *创建或编辑发运计划单
     * @param $param
     * @return array
     * @author xiejunyu
     */
    static public function create($param){
        if(empty($param['company_id_out'])||empty($param['warehouse_id_out'])
            ||empty($param['warehouse_id_rec'])||empty($param['country_id_rec'])||empty($param['list'])||empty($param['distribution_time'])
                 ||empty($param['type'])||empty($param['shop_id_rec']) ||empty($param['recieve_company'])){
            return returnArr(500,'参数不全');
        }
        $base_warehouse=ToolModel::select('base_warehouse',[],"type","","id");
        $plan=[];
        $plan['company_id_out']=$param['company_id_out'];
        $plan['warehouse_id_out']=$param['warehouse_id_out'];
        $plan['shop_id_rec']=$param['shop_id_rec'];
        $plan['warehouse_id_rec']=$param['warehouse_id_rec'];
        $plan['country_id_rec']=$param['country_id_rec'];
        $plan['distribution_time']=$param['distribution_time'];
        $plan['ctime']=TIME;
        $plan['operator']=CN_NAME;
        $plan['recieve_company']=$param['recieve_company'];//收货公司
        $plan['type']=$param['type'];//类型
        $planDetail=[];
        $pdPush=[];//标记需推送
        $msg=[];
        $sku=array_column($param['list'],'sku');
        $skuInfo=\app\common\service\SkuService::getBatchInfoBySku($sku,['cnname']);
        if(empty($skuInfo)){
            $msg[]="SKU信息获取失败!";
        }
        //海外公司 YUJISO香港有限公司 10001
        ToolModel::startTrans();
        try{
            if($param['id']){
                $id=$param['id'];
                $plan['id']=$id;
                unset($plan['ctime']);
                $planDetailOld=ToolModel::select('distribution_plan_detail',['distribution_plan_id'=>$id],'*','','id');
                ToolModel::dbInsertOrUpdate('distribution_plan',[$plan]);
            }else{
                $id=ToolModel::insertData($plan,'distribution_plan');
                $num=10000;$num+=$id;
                ToolModel::updateData(['id'=>$id],['code'=>'PS'.$num],'distribution_plan');
            }
            if(!$id){
                ToolModel::rollback();
                return returnArr(500,'生成配送单错误!');
            }
            foreach ($param['list'] as $v){
                $temp=[];
                if(empty($v)){
                    continue;
                }
                $temp['distribution_plan_id']=$id;
                $temp['utime']=TIME;
                if(empty($skuInfo[$v['sku']])){
                    $msg[]="sku:{$v['sku']}在基础资料不存在";
                    continue;
                }
                if(!empty($v['quantity'])){
                    if(!preg_match("/^[1-9][0-9]*$/",$v['quantity'])){
                        $msg[]="sku:{$v['sku']}计划数量必须为正整数";
                        continue;
                    }
                }
                if(!preg_match("/(^[0-9]\d*\.\d*|0\.\d*[1-9]\d*$)|(^[0-9]\d*$)/",$v['price'])){
                    $msg[]="sku:{$v['sku']}单价{$v['price']}必须为数字";
                    continue;
                }
                $temp['sku']=$v['sku'];
                $temp['sku_name']=$skuInfo[$v['sku']]['cnname']??'';
                $temp['price']=$v['price'];
                $temp['quantity']=$v['quantity'];
                $temp['available_stock']=$v['available_stock'];
                $planDetail[]=$temp;
            }
            if(!empty($msg)){
                ToolModel::rollback();
                return returnArr(500,$msg);
            }
            ToolModel::dbInsertOrUpdate('distribution_plan_detail',$planDetail);
            if($base_warehouse[$param['warehouse_id_out']]==2 && $base_warehouse[$param['warehouse_id_rec']]==1){
                if($param['type']==1){
                    $type=10;
                }elseif($param['type']==2){
                    $type=30;
                }
                $code=WarehousecountryService::createAdvance(['id'=>$id,'type'=>$type]);
                if($code['code']!=1){
                    ToolModel::rollback();
                    return returnArr(500,$code['msg']);
                }
            } 
            ToolModel::commit();
            if($param['id']){
                return returnArr(1,'成功');
            }else{
                return returnArr(1,'成功',['url'=>'#/Distribution/index']);
            }
        }catch (\Exception $e){
            ToolModel::rollback();
            trace($e->getMessage(),'error');
            return returnArr(600,'失败'.$e->getMessage());
        }
    }
    static public function detail($param){
        $plan[]=[];
        $detail=[];
        if(!empty($param['id'])){
            $plan=ToolModel::select('distribution_plan',['id'=>$param['id']]);
            $detail=ToolModel::select('distribution_plan_detail',['distribution_plan_id'=>$param['id']]);
            $detail=self::detailHandle($detail,$plan[0]['code']);
            $plan=self::getListHandle($plan);
        }
        $countryWarehouse=ToolModel::select('base_warehouse',[],'warehouse_name','','id');
        $company=ToolModel::select('base_company',[],'company_name','','id');
        return returnArr(1,'',['plan'=>$plan[0],'detail'=>$detail,'lsCompany'=>$company,'myCompany'=>$company,'countryWarehouse'=>$countryWarehouse]);
    }
    static public function detailHandle($detail,$code){
        foreach ($detail as &$v){
            $v['code']=$code;
        }
        return $detail;
    }
    static public function getList($param){
        if(empty($param['down'])){
            $titles=[];
        }else{
            $titles=[
                'code'=>'配送计划单号',
                'sku_num'=>'SKU',
                'company_str_out'=>'发货公司',
                'warehouse_str_out'=>'发货仓库',
                'shop_str_rec'=>'收货店铺',
                'warehouse_str_rec'=>'收货仓',
                'country_str_rec'=>'国家',
                'distribution_time'=>'配送时间',
                'type_status'=>'配送类型',
                'operator'=>'创建人',
            ];
        }
        return \app\index\model\DistributionModel::getList($param,$titles,"\app\index\service\DistributionService::getListHandle");
    }
    static public function getListHandle($data){
        $country=ConfigBase::getCountry();
        $shop=ConfigBase::getShopAll();
        $company=ConfigBase::getCompanyAll();
        $warehouse=ConfigBase::getWarehouseAll();
       
        $skuNum= \app\index\model\DistributionModel::getSKuNum(array_column($data,'id'));
        foreach ($data as &$v){
            $v['company_str_out']=$company[$v['company_id_out']];
            $v['warehouse_str_out']=$warehouse[$v['warehouse_id_out']];
            $v['shop_str_rec']=$shop[$v['shop_id_rec']];
            $v['warehouse_str_rec']=$warehouse[$v['warehouse_id_rec']];
            $v['country_str_rec']=$country[$v['country_id_rec']];
            $v['type_status']=self::$psStatus[$v['type']];
            $v['sku_num']=$skuNum[$v['id']];
            $v['recieve_str_company']=$company[$v['recieve_company']]??'';
            $v['status_text']=self::$auditStatus[$v['status']]; 
        }
        return $data;
    }
    static public function getShopWarehouse($param,$type){
        if($type==2){
           // $join=[['base_warehouse a','a.base_shop_id=b.id','left']];
           // $list=ToolModel::joinAllData('base_shop b', ['status'=>1,'base_company_id'=>$param['base_company_id']],'warehouse_name,a.id as id,b.id as base_shop_id,shop_name', $join,$pagination = False);
            $list=ToolModel::select('base_shop',['status'=>1,'base_company_id'=>$param['base_company_id']],'shop_name','','id');
           // $listout=array_column($list,'shop_name','base_shop_id');
            $listout=$list;
        }else if($type==1){
            $list=ToolModel::select('base_warehouse',['status'=>1,'base_company_id'=>$param['base_company_id']],'warehouse_name','','id');
            $listout=$list;
        }
        returnJson('1','',$listout);
    }
    static public function getWarehouseByShopId($shop_id=''){
        $sql="select w.warehouse_name,w.id,c.type from base_warehouse w left join base_company c on w.base_company_id=c.id where "
                . "w.status=1 and w.base_shop_id='{$shop_id}' limit 1";
        $result=ToolModel::queryData($sql);
        $one=isset($result[0]) ? $result[0]:[];
        returnJson('1','',$one);
    }
    static public function audit($param){
        $param['lockFunction']='\app\index\service\DistributionService::auditHandle';
        $param['lockTxt']='warehouse_country_lock';
        return ToolModel::lock($param);
    }
    //审核操作
    static public function auditHandle($param){
        if(empty($param['id'])){
            return returnArr('0','配送计划id不能为空');
        }
        $update=[
            "status"=>$param['status']
        ];
        $msg='';
        if($param['status']==1){
            $msg="提交";
        }else if($param['status']==2){
             $update["auditor"]=CN_NAME;
             $pdate["audit_time"]=date('Y-m-d H:i:s');
            $msg="审核";
        }else if($param['status']==3){
            $msg="驳回";
             $update["auditor"]=CN_NAME;
             $pdate["audit_time"]=date('Y-m-d H:i:s');
        }
        $info=ToolModel::findByAttributes('distribution_plan',['id'=>$param['id']]);
        if($info['status']==2){
            return returnArr('500',"已经审核不允许操作");
        }
        if($info['status']==3){
            return returnArr('500',"已驳回不允许操作");
        }
        $result=ToolModel::updateData(['id'=>$param['id'],"status"=>$info['status']],$update,'distribution_plan');
        if($result){
            if($param['status']==2){
                //审核通过
                if($info['type']==2){
                    //采销
                    $poRet=PurchasemanageService::createPoByDp($info);
                    if($poRet['code']!=1){
                        return returnArr(500,$poRet['msg']);
                    }
                    //生成国家仓出库单
                    $ret=WarehousecountryService::createDoByDp(['id'=>$info['id'],'type'=>30]);
                    if($ret['code']!=1){
                        return returnArr(500,$ret['msg']);
                    }
                    //生成店仓出库单
                    $retShopOut=AllocateorderService::insertAllocateorderShopwarehouseoutData(['type'=>2,'id'=>$ret['data']]);//warehouse_country_out:id
                    if($retShopOut['code']!=1){
                        return returnArr(500,$retShopOut['msg']);
                    }
                }elseif ($info['type']==1){
                    //调拨处理
                    //生成调拨单和店仓出库单 两种情况
                    $retShopOut=AllocateorderService::insertAllocateorderShopwarehouseoutData(['type'=>1,'id'=>$info['id']]);//distribution_plan:id
                    if($retShopOut['code']!=1){
                        return returnArr(500,$retShopOut['msg']);
                    }
                    $base_warehouse=ToolModel::select('base_warehouse',[],"type","","id");
                    //如果是国家仓调拨到店仓 需要生成出库单
                    if($base_warehouse[$info['warehouse_id_out']]==2 && $base_warehouse[$info['warehouse_id_rec']]==1){
                        //生成国家仓出库单 要传调拨单号
                        if(empty($retShopOut['data']['allocate_order_sn'])){
                            return returnArr(500,"调拨单号为空");
                        }
                        $ret=WarehousecountryService::createDoByDp(['id'=>$info['id'],'allocate_order_sn'=>$retShopOut['data']['allocate_order_sn'],'type'=>10]);
                        if($ret['code']!=1){
                            return returnArr(500,$ret['msg']);
                        }
                        //生成店仓出库单
                        $retShopOut=AllocateorderService::insertAllocateorderShopwarehouseoutData(['type'=>2,'id'=>$ret['data']]);//warehouse_country_out:id
                        if($retShopOut['code']!=1){
                            return returnArr(500,$retShopOut['msg']);
                        }
                    }
                }
            }elseif ($param['status']==3){
                //驳回
                //释放预占库存
                $retAdvance=WarehousecountryService::cancelAdvance($info);
                if($retAdvance['code']!=1){
                    return returnArr(500,$retAdvance['msg']);
                }
            }
             return returnArr('1',$msg.'成功',['url'=>"/#/Distribution/index"]);
        }else{
            return returnArr('0',$msg.'失败');
        }
    }
}